-- ======================================================================
-- Hell Logic Sniffer Addon 
-- 
-- Copyright 2013 Hell-Prototypes
--
-- http://www.hellprototypes.com/
-- ======================================================================
ModuleClass = "LS_PLUGIN"
ModuleName  = "FindMiniPulse"
ModuleTip   = "Find Mini Pulse by custem time"

VAR_LIMIT_TIME = "FindMiniPulse_VAR_MINI_TIME"

function get_minimum_limit_time()
	local last = LS_API.ReadVariable(VAR_LIMIT_TIME)
	if not last then last = 1000 end

	local limit_time = LS_API.InputBox(last, "Input minimum spacing time (Unit: nS)")
    if limit_time == nil then
		return 0
    end

	if last ~= limit_time then
		LS_API.SaveVariable(VAR_LIMIT_TIME, limit_time)
	end

	return limit_time
end

function get_current_channel()
	local param = LS_API.GetCommonParameter()
	if #param < 4 then
		return -1
	end

	return param[4]
end

function get_pulse_list(channel_data)
	local param = LS_API.GetCommonParameter()
	local sampling_period = param[1]
	local rawdata_index = 3
	local failling_edge_count = 0

	local last = channel_data[1]
	local pulse_list = {}
	local pulse_list_idx = 1
	while rawdata_index <= #channel_data do
		local curr = channel_data[rawdata_index]
		pulse_list[pulse_list_idx] = {time = 0, offset = 0}
		pulse_list[pulse_list_idx].time = (curr - last) * sampling_period
		pulse_list[pulse_list_idx].offset = last * sampling_period
		pulse_list_idx = pulse_list_idx + 1
		rawdata_index = rawdata_index + 2
		last = curr
	end
	
	return pulse_list
end

function time_to_readable(time_ns)
	local time_us = time_ns/1000
	local time_ms = time_us/1000
	local time_s  = time_us/1000
	
	if time_ns < 1000 then
		return string.format("%dns", time_ns)
	elseif time_us < 1000 then
		return string.format("%.3fus", time_us)
	elseif time_ms < 1000 then
		return string.format("%.3fms", time_ms)
	end
	
	return string.format("%.3fs", time_s)
end

function main ()
	local current_channel = get_current_channel()
	if current_channel < 0 then
		LS_API.MessageBox("Please select one channel")
		return
    end

	local channel_data = LS_API.GetChannelData(current_channel)
    if type(channel_data) ~= "table" then
		LS_API.MessageBox("No data found in channel : " .. current_channel)
		return
	end

	local limit_time = get_minimum_limit_time() -- ns
	if limit_time < 1 then
		return
	end
	local pulse_list = get_pulse_list(channel_data)
	
	LS_API.ReportPushBack("Found " .. #pulse_list .. ", limit_time= " .. time_to_readable(limit_time))
	for i=1, #pulse_list do
		--LS_API.ReportPushBack("pulse_list[i].time " .. pulse_list[i].time)
		if pulse_list[i].time <= limit_time then
			LS_API.ReportPushBack("@" .. time_to_readable(pulse_list[i].offset) .. ", T=" .. time_to_readable(pulse_list[i].time))
		end
	end
end

